//
// Created by SX50821 on 25-6-26.
//
#include <stdio.h>
#include <sqlite3.h>

// 回调函数用于查询结果输出
int callback(void *NotUsed, int argc, char **argv, char **azColName){
    for (int i = 0; i < argc; i++) {
        printf("%s = %s\n", azColName[i], argv[i] ? argv[i] : "NULL");
    }
    printf("\n");
    return 0;
}

int main() {
    sqlite3 *db;
    // 1. 打开或创建数据库
    int rc = sqlite3_open("E:\\download\\sqlite-tools-win-x64-3500100\\chat.db", &db);
    if (rc == SQLITE_OK)
    {
        printf("成功打开数据库\n");

    } else {
        printf("无法打开数据库\n");
        return 1;
    }

    rc = sqlite3_close(db);
    if (rc == SQLITE_OK)
    {
        printf("关闭成功\n");
    }
    else
    {
        printf("关闭失败\n");
        return 1;
    }
    char *errMsg = 0;
    // 2. 创建表
    const char *sql_create_table =
        "CREATE TABLE IF NOT EXISTS users (" \
        "id INTEGER PRIMARY KEY AUTOINCREMENT," \
        "name TEXT NOT NULL," \
        "age INT NOT NULL);";

    rc = sqlite3_exec(db, sql_create_table, 0, 0, &errMsg);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "SQL错误: %s\n", errMsg);
        sqlite3_free(errMsg);
    } else {
        printf("表创建成功\n");
    }

    // 3. 插入数据
    const char *sql_insert = "INSERT INTO users (name, age) VALUES ('Alice', 30);";
    rc = sqlite3_exec(db, sql_insert, 0, 0, &errMsg);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "插入错误: %s\n", errMsg);
        sqlite3_free(errMsg);
    } else {
        printf("插入成功\n");
    }

    // 4. 查询数据
    const char *sql_select = "SELECT * FROM users;";
    printf("查询结果:\n");
    rc = sqlite3_exec(db, sql_select, callback, 0, &errMsg);
    if (rc != SQLITE_OK) {
        fprintf(stderr, "查询错误: %s\n", errMsg);
        sqlite3_free(errMsg);
    }

    // 5. 关闭数据库
    sqlite3_close(db);
    return 0;
}
